package com.common.handler.exception;

import com.common.domain.entity.ResponseResult;
import com.common.enums.AppHttpCodeEnum;
import com.common.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author 
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SystemException.class)
    public ResponseResult systemExceptionHandler(SystemException e) {
        //打印异常信息
        log.error("出现了异常！ {}", e);
        //从异常对象中获取提示信息封装返回
        return ResponseResult.errorResult(e.getCode(), e.getMsg());
    }

    /**
     * 方法参数校验
     * 由于spring捕获异常的问题，导致此异常的编码格式无法修改为UTF-8，
     * 故不使用RestControlle的ResponseBody,自己实现httpServletResponse的IO。
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        final BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        String msg = AppHttpCodeEnum.VALIDATION_ERROR.getMsg();
        if (!fieldErrors.isEmpty()) {
            // 返回错误信息
            msg = msg + ":" + fieldErrors.get(0).getDefaultMessage();
        }
        log.error(e.getMessage(), e);
        return ResponseResult.errorResult(AppHttpCodeEnum.VALIDATION_ERROR, msg.isEmpty() ? e.getCause().getMessage() : msg);
    }
}
